<?php

declare(strict_types=1);

namespace app\extend\adapter;

use Exception;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * 七牛云oss
 * composer require qiniu/php-sdk
 */
class QiniuAdapter
{
    public readonly array $config;

    private $client;

    public function __construct($config)
    {
        $this->config = $config;
    }

    private function init() {
        $this->client = new Auth($this->config['accessKey'], $this->config['secretKey']);
    }
    /**
     * 上传
     */
    public function upload(string $path, string $url)
    {
        try{
            $this->init();
            $token = $this->client->uploadToken($this->config['bucket']);
            $uploadObj = new UploadManager();
            list($ret, $error) = $uploadObj->putFile($token, $url, $path);
            if($error !== null) {
                tips($error->message());
            }
        } catch (Exception $e) {
            tips($e->getMessage());
        }
    }
    /**
     * 下载
     */
    public function download(string $url, string $save_path)
    {
        try{
            $this->init();
            $buckerMgr = new BucketManager($this->client);
            list($ret, $error) = $buckerMgr->stat($this->config['bucket'], $url);
            if($error !== null) {
                tips($error->message());
            }
        } catch (Exception $e) {
            tips($e->getMessage());
        }
    }
    /**
     * 删除
     */    
    public function delete(string $url)
    {
        try{
            $this->init();
            $buckerMgr = new BucketManager($this->client);
            list($ret, $error) = $buckerMgr->delete($this->config['bucket'], $url);
            if($error !== null) {
                tips($error->message());
            }
        } catch (Exception $e) {
            tips($e->getMessage());
        }
    }
}